React = require('react')
timerMixin = require('react-timer-mixin')
{StyleSheet,Platform,AsyncStorage,View,Image,Text,Navigator,BackAndroid,TouchableOpacity,Alert,StatusBar,NetInfo,AppState} = require('react-native')


{Provider,connect} = require('react-redux')
{Router,Route,hashHistory,IndexRoute,browserHistory} = require('react-router')
# {syncHistoryWithStore} = require('react-router-redux')

Home = require('./pages/home.js')
InPlan = require('./pages/inplan.js')
Dimensions = require('Dimensions')
{ width, height } = Dimensions.get('window')
if Platform.OS is 'android'
  height = height-StatusBar.currentHeight



Icon = require('antd-mobile/lib/icon')
Toast = require('antd-mobile/lib/toast')
_ = require('underscore')
codePush = require('react-native-code-push')

pages =[
  'game'
  'jkjh'
  'ckjh'
  'ybjh'
  'jkdd'
  'ckdd'
  'ybdd'
  'settings'
  'ckblbb'
  'dddbrz'
  'hdss'
  'dqdm'
  'tz'
  'yhypm'
  'gcsj'
  'zygg'
  'tzygg'
  'yhygf'
  'ygxlxsq'
  'llmtxx'
  'gxlxsq'
  'bwss'
  'gkcsb'
  'yhsj'
  'hxjg'
  'yhyqr'
  'ckjl'
  'scdzqz'

]
store = null

global.SaveAppData = ->
  setTimeout ->
    cState = store.getState()
    str = JSON.stringify cState
    AsyncStorage.setItem 'appData',str,(err)->
      if err
        Toast.fail("缓存数据保存失败！")
  ,500

App = React.createClass
  mixins:[timerMixin]
  getInitialState:->
    debugger
    #异步加载缓存数据，若成功则
    that = @
    AsyncStorage.getItem 'appData',(err,result)->
      if err
        store = require('./store/configureStore.js')
        that.setState storeInitCompleted:true
      else
        if result
          data = JSON.parse(result)
          global.appData = data
        #更新网络状态
        NetInfo.isConnected.fetch().done (status)->
          global.appData?.appState?.connected = status
          # global.appData?.appState?.connected = status not in ['NONE','DUMMY','UNKNOWN']
          store = require('./store/configureStore.js')
          that.setState storeInitCompleted:true

    {
      storeInitCompleted:false
    }

    # AsyncStorage.getItem('appData')
    # .then (result)->
    #   if result
    #     data = JSON.parse(result)
    #     global.appData = data
    #     #更新网络状态
    #     NetInfo.fetch().done (status)->
    #       global.appData.appState.connected = status not in ['NONE','DUMMY','UNKNOWN']
    #       store = require('./store/configureStore.js')
    #       that.setState storeInitCompleted:true
    #   else
    #     store = require('./store/configureStore.js')
    #     that.setState storeInitCompleted:true


  componentDidMount:->
    that = @
    debugger
    @NetListener = NetInfo.isConnected.addEventListener 'change',(status)->
      if status
          Toast.info('网络已连接') if that.state.storeInitCompleted
          store?.dispatch {
            type:'MAPPSTATE/CONNECTION'
            payload:status
          }
      else
          Toast.info('网络连接断开') if that.state.storeInitCompleted
          store?.dispatch {
            type:'MAPPSTATE/CONNECTION'
            payload:status
          }
      # debugger
      # if status in ['NONE','DUMMY','UNKNOWN']
      #   Toast.info('网络连接断开') if that.state.storeInitCompleted
      #   store?.dispatch {
      #     type:'MAPPSTATE/CONNECTION'
      #     payload:status
      #   }
      # else
      #   Toast.info('网络已连接') if that.state.storeInitCompleted
      #   store?.dispatch {
      #     type:'MAPPSTATE/CONNECTION'
      #     payload:status
      #   }


    BackAndroid.addEventListener 'hardwareBackPress',(e)->
      navigator = that._navigator
      if navigator?.getCurrentRoutes().length>1
        navigator.pop()
      else
        if that.backBtnAlreadyClick is true
          cState = store.getState()
          str = JSON.stringify cState
          AsyncStorage.setItem 'appData',str,(err)->
            if err
              Toast.fail("缓存数据保存失败！")
            else
              BackAndroid.exitApp()
        else
          that.backBtnAlreadyClick = true
          Toast.info('再按一次退出应用')
          that.setTimeout ->
            that.backBtnAlreadyClick = false
          ,3000
      true
    @appStateListener = AppState.addEventListener 'change',(state)->
                          if state is 'background'
                            cState = store.getState()
                            str = JSON.stringify cState
                            AsyncStorage.setItem 'appData',str,(err)->
                              if err
                                Toast.fail("缓存数据保存失败！")

  componentWillUnmount:->
    BackAndroid.removeEventListener('hardwareBackPress')
    NetInfo.isConnected.removeEventListener('change',@NetListener)
    AppState.removeEventListener('change',appStateListener)
  render:->
    # 动态设定转场效果
    # configureScene ={ (route,navigator)->
    #     Navigator.SceneConfigs.FloatFromBottom
    # }
    that = @
    if @state.storeInitCompleted
      <Provider store={store}>
        <Image style={{width:width,height:height}} source={require('./img/background.png')}>
          <StatusBar hidden={false} translucent={false} animated={false}/>
          <Navigator
            initialRoute={{
              name: 'Home'
              component: Home
              }}
            configureScene={(route)->
              if route.name in pages
                Navigator.SceneConfigs.FloatFromBottomAndroid
              else
                Navigator.SceneConfigs.PushFromRight
            }
            renderScene={(route, navigator) ->
              that._navigator ?= navigator
              Component = route.component
              `<Component {...route.params} navigator={navigator} />`
            }
            />
        </Image>
      </Provider>
    else
      <View></View>
# sceneStyle={{marginTop:20}}

# 动态状态栏的写法
# ` <View>
#     <StatusBar hidden={false} translucent={true} animated={true}/>
#     <Component {...route.params} navigator={navigator} />
#   </View>`

styles = StyleSheet.create
          scene:
            flex:1
            marginTop:10

updateDialogOption =
  title:'程序更新'
  appendReleaseDescription:true
  descriptionPrefix:'\n\n更新内容：\n'
  mandatoryUpdateMessage:'此更新为强制更新'
  mandatoryContinueButtonLabel:'继续'
  optionalIgnoreButtonLabel:'取消'
  optionalInstallButtonLabel:'确定'
  optionalUpdateMessage :'有新的更新可用，是否更新？'


App = codePush({ updateDialog: updateDialogOption, installMode: codePush.InstallMode.IMMEDIATE,deploymentKey: 'f3Cmmohcgc7iRP0Vj7E-5Eif6VVKN1ftSZjVf' })(App)
module.exports = App
